package com.ikangtai.shecare.home.calendar;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.Constant;
import com.ikangtai.shecare.common.EnConstant;
import com.ikangtai.shecare.common.eventBusMsg.ChooseDate;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.record.bean.UserRecordData;
import com.jaeger.library.StatusBarUtil;

import org.simple.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 日历显示activity
 *
 * @author Vincent Lee
 */
public class CalendarActivity extends BaseActivity implements View.OnClickListener {
    private List<DayState> dayStates;
    private List<UserRecordData> userRecordDatas;
    private TextView lunarYearMonthText;
    private GestureDetector gestureDetector = null;
    private RelativeLayout li_top, states0, states1;
    private CalendarAdapter calV = null;
    private ViewFlipper flipper = null;
    private GridView gridView = null;
    private ImageButton btnBack, btnRecord;
    private static int jumpMonth = 0; // 每次滑动，增加或减去一个月,默认为0（即显示当前月）
    private static int jumpYear = 0; // 滑动跨越一年，则增加或者减去一年,默认为0(即当前年)
    private int year_c = 0;
    private int month_c = 0;
    private int day_c = 0;
    private String currentDate = "";
    private String chooseDate;
    private int mLastPosition;
    private ImageButton btnCurrent;
    private ProgressDialog progressDialog;

    /**
     * 每次添加gridview到viewflipper中时给的标记
     */
    private int gvFlag = 0;
    /**
     * 当前的年月，现在日历顶端
     */
    private TextView currentMonth;
    /**
     * 上个月
     */
    private ImageView prevMonth;
    /**
     * 下个月
     */
    private ImageView nextMonth;

    public CalendarActivity() {

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
        currentDate = sdf.format(date); // 当期日期
        year_c = Integer.parseInt(currentDate.split("-")[0]);
        month_c = Integer.parseInt(currentDate.split("-")[1]);
        day_c = Integer.parseInt(currentDate.split("-")[2]);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        android.os.Debug.startMethodTracing();
        setContentView(R.layout.activity_calendar);
        EventBus.getDefault().register(this);


        progressDialog = new ProgressDialog(this);
        li_top = (RelativeLayout) findViewById(R.id.li_top);
        lunarYearMonthText = (TextView) this.findViewById(R.id.tvLunarYearMonth);
        btnRecord = (ImageButton) findViewById(R.id.btnRecord);
        btnBack = (ImageButton) findViewById(R.id.btnBack);
        btnCurrent = (ImageButton) findViewById(R.id.btnCurrent);
        currentMonth = (TextView) findViewById(R.id.currentMonth);
        prevMonth = (ImageView) findViewById(R.id.prevMonth);
        nextMonth = (ImageView) findViewById(R.id.nextMonth);
        states0 = (RelativeLayout) findViewById(R.id.states0);
        progressDialog.setMessage(getString(R.string.webcfg_dialog));
        progressDialog.show();
        setListener();
        Observable.create(new Observable.OnSubscribe<List<DayState>>() {

            @Override
            public void call(Subscriber<? super List<DayState>> subscriber) {
                subscriber.onNext(getDayStates());
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<DayState>>() {
                               @Override
                               public void onCompleted() {

                               }

                               @Override
                               public void onError(Throwable e) {

                               }

                               @Override
                               public void onNext(List<DayState> strings) {
                                   setListener();

                                   Intent intent = getIntent();
                                   String dateRecord = intent.getStringExtra("dateRecord");
                                   AppLog.i("dateRecord = " + dateRecord);

                                   if (dateRecord != null) {
                                       jumpMonth = 0;

                                       year_c = Integer.valueOf(dateRecord.split("\\.")[0]);
                                       AppLog.i("dateRecord year_c = " + year_c);

                                       String tempStr = dateRecord.split("\\.")[1];
                                       month_c = Integer.valueOf(getStr2Num(tempStr));
                                       AppLog.i("dateRecord month_c3 = " + month_c);

                                       String tempStr2 = dateRecord.split("\\.")[2];
                                       day_c = Integer.valueOf(getStr2Num(tempStr2));
                                       AppLog.i("dateRecord day_c = " + day_c);

                                       btnCurrent.setVisibility(View.VISIBLE);
                                       flipper = (ViewFlipper) findViewById(R.id.flipper);
                                       flipper.removeAllViews();
                                       calV = new CalendarAdapter(CalendarActivity.this, getResources(), jumpMonth, jumpYear, year_c, month_c, day_c, dayStates);
                                       addGridView();
                                       gridView.setAdapter(calV);
                                       flipper.addView(gridView, 0);


                                       if (progressDialog != null && progressDialog.isShowing()) {
                                           progressDialog.dismiss();
                                           progressDialog = null;
                                       }

                                   } else {
                                       flipper = (ViewFlipper) findViewById(R.id.flipper);
                                       flipper.removeAllViews();
                                       calV = new CalendarAdapter(CalendarActivity.this, getResources(), jumpMonth, jumpYear, year_c, month_c, day_c, dayStates);
                                       addGridView();
                                       gridView.setAdapter(calV);
                                       flipper.addView(gridView, 0);


                                       if (jumpMonth == 0) {
                                           btnCurrent.setVisibility(View.GONE);
                                       }

                                       if (progressDialog != null && progressDialog.isShowing()) {
                                           progressDialog.dismiss();
                                           progressDialog = null;
                                       }

                                       enterCurrentMonth(0);
                                   }

                                   StringBuffer textDate = new StringBuffer();

                                   textDate.append(calV.getShowYear()).append(getString(R.string.year)).append(calV.getShowMonth()).append(getString(R.string.month)).append("\t");
                                   currentMonth.setText(textDate);

                                   switch (Locale.getDefault().getLanguage()) {
                                       case "zh":
                                           textDate.append(calV.getShowYear()).append(getString(R.string.year)).append(calV.getShowMonth()).append(getString(R.string.month)).append("\t");
                                           lunarYearMonthText.setText(textDate);
                                           lunarYearMonthText.setText(LunarCalendar.cyclical(Integer.valueOf(calV.getShowYear()))
                                                   + LunarCalendar.animalsYear(Integer.valueOf(calV.getShowYear()))
                                                   + (getString(R.string.year)) + (calV.getShowMonthChina()));
                                           break;
                                       default:
                                           lunarYearMonthText.setVisibility(View.GONE);
//                                           textDate.append(calV.getShowYear()).append(calV.getShowMonth()).append("\t");
//                                           lunarYearMonthText.setText(textDate);
//                                           lunarYearMonthText.setText(LunarCalendar.cyclical(Integer.valueOf(calV.getShowYear()))
//                                                   + LunarCalendar.animalsYear(Integer.valueOf(calV.getShowYear()))
//                                                   + (getString(R.string.year)) + (calV.getShowMonthChina()));

                                   }
                               }
                           }

                );


    }


    private class MyGestureListener extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            int gvFlag = 0; // 每次添加gridview到viewflipper中时给的标记
            if (e1.getX() - e2.getX() > 120) {
                // 像左滑动
                enterNextMonth(gvFlag);
                return true;
            } else if (e1.getX() - e2.getX() < -120) {
                // 向右滑动
                enterPrevMonth(gvFlag);
                return true;
            }
            return false;
        }

    }

    private String getStr2Num(String str){
        String numStr = str;

        if(str.charAt(0) == '0')
            numStr = str.substring(1);

        return numStr;
    }

    /**
     * 移动到当前月
     *
     * @param gvFlag
     */

    private void enterCurrentMonth(int gvFlag) {
        addGridView(); // 添加一个gridView
        btnCurrent.setVisibility(View.GONE);

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
        currentDate = sdf.format(date); // 当期日期
        year_c = Integer.parseInt(currentDate.split("-")[0]);
        month_c = Integer.parseInt(currentDate.split("-")[1]);
        day_c = Integer.parseInt(currentDate.split("-")[2]);

        calV = new CalendarAdapter(this, this.getResources(), 0, 0, year_c, month_c, day_c, dayStates);
        gridView.setAdapter(calV);
        if (jumpMonth < 0) {
            jumpMonth = 0;
            addTextToTopTextView(currentMonth); // 移动到下一月后，将当月显示在头标题中
            gvFlag++;
            flipper.addView(gridView, gvFlag);
            flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in));
            flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out));
            flipper.showNext();
            flipper.removeViewAt(0);
        } else {
            jumpMonth = 0;
            addTextToTopTextView(currentMonth); // 移动到下一月后，将当月显示在头标题中
            gvFlag++;
            flipper.addView(gridView, gvFlag);
            flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_in));
            flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_out));
            flipper.showPrevious();
            flipper.removeViewAt(0);
        }


    }

    /**
     * 移动到下一个月
     *
     * @param gvFlag
     */

    private void enterNextMonth(int gvFlag) {
        addGridView(); // 添加一个gridView
        jumpMonth++; // 下一个月
        btnCurrent.setVisibility(View.VISIBLE);
        calV = new CalendarAdapter(this, this.getResources(), jumpMonth, jumpYear, year_c, month_c, day_c, dayStates);
        gridView.setAdapter(calV);
        addTextToTopTextView(currentMonth); // 移动到下一月后，将当月显示在头标题中
        gvFlag++;
        flipper.addView(gridView, gvFlag);
        flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_in));
        flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_left_out));
        flipper.showNext();
        flipper.removeViewAt(0);
    }


    /**
     * 移动到上一个月
     *
     * @param gvFlag
     */
    private void enterPrevMonth(int gvFlag) {
        addGridView(); // 添加一个gridView
        jumpMonth--; // 上一个月
        btnCurrent.setVisibility(View.VISIBLE);
        calV = new CalendarAdapter(this, this.getResources(), jumpMonth, jumpYear, year_c, month_c, day_c, dayStates);
        gridView.setAdapter(calV);
        gvFlag++;
        addTextToTopTextView(currentMonth); // 移动到上一月后，将当月显示在头标题中
        flipper.addView(gridView, gvFlag);

        flipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_in));
        flipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_right_out));
        flipper.showPrevious();
        flipper.removeViewAt(0);
    }

    /**
     * 添加头部的年份 闰哪月等信息
     *
     * @param view
     */


    public void addTextToTopTextView(TextView view) {


        switch (Locale.getDefault().getLanguage()) {
            case "zh":
                StringBuffer textDate = new StringBuffer();
                textDate.append(calV.getShowYear()).append(getString(R.string.year)).append(calV.getShowMonth()).append(getString(R.string.month)).append("\t");
                view.setText(textDate);
                lunarYearMonthText.setText(LunarCalendar.cyclical(Integer.valueOf(calV.getShowYear()))
                        + LunarCalendar.animalsYear(Integer.valueOf(calV.getShowYear()))
                        + (getString(R.string.year)) + (calV.getShowMonthChina()));
                break;
            default:
                StringBuffer textDateen = new StringBuffer();
                textDateen.append(calV.getShowYear() + "." + calV.getShowMonth()).append("\t");
                view.setText(textDateen);
                lunarYearMonthText.setVisibility(View.GONE);
//                lunarYearMonthText.setText(LunarCalendar.cyclical(Integer.valueOf(calV.getShowYear()))
//                        + LunarCalendar.animalsYear(Integer.valueOf(calV.getShowYear()))
//                        + (getString(R.string.year)) + (calV.getShowMonthChina()));
//        }
        }

    }

    private void addGridView() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsoluteLayout.LayoutParams.MATCH_PARENT);
        // 取得屏幕的宽度和高度
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int Width = display.getWidth();
        int Height = display.getHeight();

        gridView = new GridView(this);
        gridView.setNumColumns(7);
        gridView.setColumnWidth(40);
        // gridView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
        if (Width == 720 && Height == 1280) {
            gridView.setColumnWidth(40);
        }
        gridView.setGravity(Gravity.CENTER_VERTICAL);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        // 去除gridView边框
        gridView.setVerticalSpacing(1);
        gridView.setHorizontalSpacing(1);
        gridView.setOnTouchListener(new View.OnTouchListener() {
            // 将gridview中的触摸事件回传给gestureDetector

            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                return CalendarActivity.this.gestureDetector.onTouchEvent(event);
            }
        });

        gridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
                // TODO Auto-generated method stub
//                 点击任何一个item，得到这个item的日期(排除点击的是周日到周六(点击不响应))
                int startPosition = calV.getStartPositon();
                int endPosition = calV.getEndPosition();
                if (startPosition <= position + 7 && position <= endPosition - 7) {
                    String scheduleDay = calV.getDateByClickItem(position).split("\\.")[0]; // 这一天的阳历
                    // String scheduleLunarDay =
                    // calV.getDateByClickItem(position).split("\\.")[1];
                    // //这一天的阴历
                    String scheduleYear = calV.getShowYear();
                    String scheduleMonth = calV.getShowMonth();

                    chooseDate = scheduleYear + "-" + scheduleMonth + "-" + scheduleDay;
//                    Toast.makeText(CalendarActivity.this, "点击了该条目" + position +"222"+ arg3,
//                            Toast.LENGTH_SHORT).show();

                    calV.setSeclection(position);
                    calV.notifyDataSetChanged();


                }
            }
        });
        gridView.setLayoutParams(params);
        StatusBarUtil.setColor(this, getResources().getColor(getBGColor(dayStates.get(App.getPreferenceInt(Constant.kCurrentPosition)).getState())), 0);
        li_top.setBackgroundColor(getResources().getColor(getBGColor(dayStates.get(App.getPreferenceInt(Constant.kCurrentPosition)).getState())));

    }

    private void setListener() {
        gestureDetector = new GestureDetector(this, new MyGestureListener());
        btnCurrent.setOnClickListener(this);
        btnCurrent.setOnClickListener(this);
        btnRecord.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        prevMonth.setOnClickListener(this);
        nextMonth.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btnCurrent:
                enterCurrentMonth(0);

                break;
            case R.id.nextMonth: // 下一个月
                enterNextMonth(gvFlag);
                break;
            case R.id.prevMonth: // 上一个月
                enterPrevMonth(gvFlag);
                break;
            case R.id.btnBack:
                finish();
                break;
            case R.id.btnRecord:
                if (chooseDate == null) {
                    chooseDate = dayStates.get(App.getPreferenceInt(Constant.kCurrentPosition)).getDay();
                }
                EventBus.getDefault().post(new ChooseDate(chooseDate));
                finish();
                break;

            default:
                break;
        }
    }

    private String getCalendarState(int i) {
        switch (App.dayUnitDSOutputsList.get(i).getPeriod(App.status) + "") {
            case "yjq":
                return getString(R.string.menstruation);
            case "lpq":
                return getString(R.string.follicular_phase);
            case "htq":
                return getString(R.string.luteal);
            case "jhaqq":
                return getString(R.string.safe);
            case "wxq":
                return getString(R.string.dangerous);
            case "jqaqq":
                return getString(R.string.safe);
            case "aqq":
                return getString(R.string.safe);
            default:
                if (App.dayUnitDSOutputsList.get(i).homePageOvulation > 0) {
                    return getString(R.string.ovulation);
                } else if (App.dayUnitDSOutputsList.get(i).homePageOvulation == 0) {
                    return getString(R.string.ovulation_day);
                } else {
                    return getString(R.string.after_ovulation);
                }
        }

    }


    private int getBGColor(String state) {
        switch (Locale.getDefault().getLanguage()) {
            case "zh":
                switch (state) {
                    case Constant.kMenstruation:
                        return R.color.circle_bg_pink;
                    case Constant.kOvulation:
                        return R.color.circle_bg_green;
                    case Constant.kOvulationday:
                        return R.color.circle_bg_yellow;
                    default:
                        return R.color.lpq_color;
                }
            default:
                switch (state) {
                    case EnConstant.kMenstruation:
                        return R.color.circle_bg_pink;
                    case EnConstant.kOvulation:
                        return R.color.circle_bg_green;
                    case EnConstant.kOvulationday:
                        return R.color.circle_bg_yellow;
                    default:
                        return R.color.lpq_color;
                }
        }
    }

    public List<DayState> getDayStates() {

        dayStates = new ArrayList<>();
        userRecordDatas = new ArrayList<>();
        userRecordDatas = UserRecordData.getUserRecordDataList(this, App.userName, App.dayUnitDSOutputsList.get(0).date, App.dayUnitDSOutputsList.get(App.dayUnitDSOutputsList.size() - 1).date);
        for (int i = 0; i < App.dayUnitDSOutputsList.size(); i++) {
            dayStates.add(new DayState(DateUtil.getDateStr(App.dayUnitDSOutputsList.get(i).date), getCalendarState(i), userRecordDatas.get(i).isCopulationHaveSex()));
        }
        return dayStates;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
//        android.os.Debug.stopMethodTracing();
    }


}
